package com.globo.opensocial;

import jargs.gnu.CmdLineParser;
import jargs.gnu.CmdLineParser.IllegalOptionValueException;
import jargs.gnu.CmdLineParser.UnknownOptionException;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * Main Class
 * 
 * @author falcao
 * 
 */
public class OpenSocialGenerator {

	/**
	 * Main Melhod.
	 * 
	 * @param args
	 */
	public static void main(String[] args) {

		// Command line options.
		CmdLineParser parser = new CmdLineParser();
		CmdLineParser.Option hostOpt = parser.addStringOption("host");
		CmdLineParser.Option debugOpt = parser.addBooleanOption("debug");
		CmdLineParser.Option charsetOpt = parser.addStringOption("charset");
		CmdLineParser.Option outputOpt = parser.addStringOption("output");

		// try parse the line options.
		try {
			parser.parse(args);
		} catch (IllegalOptionValueException e) {
			usage();
		} catch (UnknownOptionException e) {
			usage();
		}

		Application app;
		try {
			app = new Application();

			// Debug mode
			// this options don't optimize the code and don't remove the
			// console.debug calls
			Boolean debug = (Boolean) parser.getOptionValue(debugOpt,
					Boolean.FALSE);
			app.setDebug(debug);

			// Set the charset.
			String charset = (String) parser.getOptionValue(charsetOpt);
			if (charset == null || !Charset.isSupported(charset)) {
				charset = System.getProperty("file.encoding");
				if (charset == null) {
					charset = "UTF-8";
				}
			}
			System.out.println("[INFO] Using charset " + charset);
			app.setCharset(charset);

			// Configure the output file name.
			String output = (String) parser.getOptionValue(outputOpt);
			if (output != null) {
				app.setOutput(output);
			}

			// Set the basehost.
			String host = (String) parser.getOptionValue(hostOpt);
			if (host != null) {
				app.setHost(host);
			} else {
				usage();
			}
			System.out.println("[INFO] Host: " + host);

			// Set the javascript application code.
			String files[] = parser.getRemainingArgs();
			if (files.length != 1) {
				usage();
			}
			File file = new File(files[0]);
			if (!file.isFile()) {
				usage();
			}
			System.out.println("[INFO] Loading " + files[0]);
			app.setCode(file);

			app.build();
			app.write();
			//app.writeTests();
			
		} catch (IOException e) {
			System.err.println("[ERRO] Erro on built application ");
			e.printStackTrace();
		} catch (Exception e) {
			System.err.println("[ERRO] Erro on built application ");
			e.printStackTrace();
		}
	}

	/**
	 * Show cmd line options TODO:
	 */
	private static void usage() {
		System.out
				.println("Use: java osg-x.y.z.jar [--debug] --host=http://somehost/somepath [--output=file.xml] [--charset=UTF8] application.js");
		System.exit(1);
	}

}
